<%# encoding: utf-8%>
$(function() {
  if ($('body').hasClass('apps') && $('body').hasClass('show')) {
    $('#apps-menu-link').addClass('menu-current');
    appInstancesTable_Settings = {
      'bAutoWidth':      false,
      'bLengthChange':   false,
      'bStateSave':      false,
      'oLanguage':       dataTables_lang,
      'sPaginationType': 'full_numbers',
      'aoColumnDefs':    [{'bSearchable': false, 'aTargets': [7]},
                          {'bSortable': false, 'aTargets': [7]}]
    };
    appInstancesTable = $('#app-instances-table').dataTable(appInstancesTable_Settings);
    appCrashesTable_Settings = {
      'bAutoWidth':      false,
      'bLengthChange':   false,
      'bStateSave':      false,
      'oLanguage':       dataTables_lang,
      'sPaginationType': 'full_numbers',
      'aaSorting':       [[ 1, 'desc']]
    };
    appCrashesTable = $('#app-crashes-table').dataTable(appCrashesTable_Settings);
    appServicesTable_Settings = {
      'bAutoWidth':      false,
      'bLengthChange':   false,
      'bStateSave':      false,
      'oLanguage':       dataTables_lang,
      'sPaginationType': 'full_numbers',
      'aoColumnDefs':    [{'bSearchable': false, 'aTargets': [3]},
                          {'bSortable': false, 'aTargets': [3]},
                          {'sType': 'string', 'aTargets': [1]}
                         ]
    };
    appServicesTable = $('#app-services-table').dataTable(appServicesTable_Settings);
    appUrlsTable_Settings = {
      'bAutoWidth':      false,
      'bLengthChange':   false,
      'bStateSave':      false,
      'oLanguage':       dataTables_lang,
      'sPaginationType': 'full_numbers',
      'aoColumnDefs':    [{'bSearchable': false, 'aTargets': [1]},
                          {'bSortable': false, 'aTargets': [1]}
                         ]
    };
    appUrlsTable = $('#app-urls-table').dataTable(appUrlsTable_Settings);
    var ultabs = $('ul.tabs');
    ultabs.tabs('div.panels > div.panel', {
      effect: 'slide',
      tabs: 'li',
      onClick: function(event, tabIndex) {
        var tab = this.getCurrentTab().find('a').attr('href');
        if (tab == '#resources') {
          $('.invoke-modalBox').empty().hide();
          $.editable.addInputType('range', {
            element: function(settings, original) {
              var input = jQuery('<input type="range" />');
              $(this).append(input);
              return(input);
            },
            plugin: function(settings, original) {
              if (typeof rangeapi == 'undefined') {
                value = resources_instances;
              } else {
                value = rangeapi.getValue()
              }
              var range = $(':range', this).rangeinput({'min': 1, 'max': resources_available_instances});
              rangeapi = range.data("rangeinput");
              rangeapi.setValue(value)
            }
          });
          $('td#instances-' + resources_appname + '.editableText').editable(app_set_instances_url, {
            'method'   : 'PUT',
            'name'     : 'instances',
            'type'     : 'range',
            'submit'   : I18n.t('assets.js.update'),
            'cancel'   : I18n.t('assets.js.cancel'),
            'indicator': '<%= image_tag('wait.gif') %>',
            'tooltip'  : I18n.t('assets.js.click2edit'),
            'callback'  : function(value, settings) {
              var row = $(this.parentNode).addClass('highlight').hide();
              row.fadeIn(1800, function() {
                $(this).removeClass('highlight');
              });
              $('#flash-content').empty();
            },
            'submitdata' : function(value, settings) {
              var value = rangeapi.getValue();
              return {'instances': value};
            },
            'onerror'   : function(settings, original, xhr) {
              original.reset();
              $('#flash-content').empty();
              $('#flash-content').append('<div class="alert">Error ' + xhr.status + ': ' + xhr.responseText + '</div>');
              $('#flash').fadeIn('slow');
            }
          });
          $('td#memory-' + resources_appname + '.editableText').editable(app_set_memsize_url, {
            'method'   : 'PUT',
            'name'     : 'memsize',
            'type'     : 'select',
            'submit'   : I18n.t('assets.js.update'),
            'cancel'   : I18n.t('assets.js.cancel'),
            'indicator': '<%= image_tag('wait.gif') %>',
            'tooltip'  : I18n.t('assets.js.click2edit'),
            'data'     : resources_available_memsizes,
            'callback' : function(value, settings) {
              var row = $(this.parentNode).addClass('highlight').hide();
              row.fadeIn(1800, function() {
                $(this).removeClass('highlight');
              });
              $('#flash-content').empty();
            },
            'onerror'  : function(settings, original, xhr) {
              original.reset();
              $('#flash-content').empty();
              $('#flash-content').append('<div class="alert">Error ' + xhr.status + ': ' + xhr.responseText + '</div>');
              $('#flash').fadeIn('slow');
            }
          });
        }
        if (tab == '#instances') {
          $('.invoke-modalBox').empty().hide();
          view_log_trigger = $('.viewLog').overlay({
            'closeOnClick': false,
            'fixed': false,
            'left': 'left',
            'mask': {color: '#404040', loadSpeed: 'normal', opacity: 0.7},
            'top': '5%',
            'onBeforeLoad': function(event) {
              $('.modalBox-flash').empty();
              var wrap = this.getOverlay().find(".modalLog");
              wrap.load(this.getTrigger().attr("href"));
            }
          });
        }
        if (tab == '#crashes') {
          $('.invoke-modalBox').empty().hide();
        }
        if (tab == '#envvars') {
          $('.invoke-modalBox').html('<button class="addEnvvar" rel="#add_envvar_modalBox">' + I18n.t('apps.js.add_envvar') + '</button>').show();
          if (typeof appEnvvarsTable == 'undefined') {
            appEnvvarsTable_Settings = {
              'bAutoWidth':      false,
              'bLengthChange':   false,
              'bStateSave':      false,
              'oLanguage':       dataTables_lang,
              'sPaginationType': 'full_numbers',
              'aoColumnDefs':    [{'bSearchable': false, 'aTargets': [2]},
                                  {'bSortable': false, 'aTargets': [2]}
                                 ],
              'fnDrawCallback':  function() {
                $('td.editableText').editable(app_set_var_url, {
                  'method'    : 'PUT',
                  'name'      : 'var_value',
                  'type'      : 'text',
                  'submit'    : I18n.t('assets.js.update'),
                  'cancel'    : I18n.t('assets.js.cancel'),
                  'indicator' : '<%= image_tag('wait.gif') %>',
                  'tooltip'   : I18n.t('assets.js.click2edit'),
                  'placeholder' : I18n.t('assets.js.click2edit'),
                  'callback'  : function(value, settings) {
                    var aPos = appEnvvarsTable.fnGetPosition(this);
                    var row = $(this.parentNode).addClass('highlight').hide();
                    row.fadeIn(1800, function() {
                      $(this).removeClass('highlight');
                    });
                    appEnvvarsTable.fnUpdate(value, aPos[0], aPos[1]);
                    $('#flash-content').empty();
                  },
                  'submitdata': function(value, settings) {
                    return {
                      'edit'   : true,
                      'restart': true,
                      'id'     : this.parentNode.getAttribute('id')
                    };
                  },
                  'onerror'   : function(settings, original, xhr) {
                    original.reset();
                    $('#flash-content').empty();
                    $('#flash-content').append('<div class="alert">Error ' + xhr.status + ': ' + xhr.responseText + '</div>');
                    $('#flash').fadeIn('slow');
                  }
                });
              }
            };
            appEnvvarsTable = $('#app-envvars-table').dataTable(appEnvvarsTable_Settings);
          }
          addEnvvar_trigger = $('.addEnvvar').overlay({
            'closeOnClick': false,
            'mask': {color: '#404040', loadSpeed: 'normal', opacity: 0.7},
            'top': '25%',
            'onBeforeLoad': function(event) {
              $('.modalBox-flash').empty();
            }
          });
          $('#app-envvars-table .icon-tip').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
        }
        if (tab == '#services') {
          $('.invoke-modalBox').html('<button class="bindService" rel="#bind_service_modalBox">' + I18n.t('apps.js.add_service') + '</button>').show();
          bindService_trigger = $('.bindService').overlay({
            'closeOnClick': false,
            'mask': {color: '#404040', loadSpeed: 'normal', opacity: 0.7},
            'top': '25%',
            'onBeforeLoad': function(event) {
              $('.modalBox-flash').empty();
            }
          });
          if (typeof service_chosen == 'undefined') {
            service_chosen = $('.service-chosen').chosen({'no_results_text': I18n.t('assets.js.no_results')});
          }
          $('#app-services-table .icon-tip').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
        }
        if (tab == '#urls') {
          $('.invoke-modalBox').html('<button class="addURL" rel="#add_url_modalBox">' + I18n.t('apps.js.add_url') + '</button>').show();
          addURL_trigger = $('.addURL').overlay({
            'closeOnClick': false,
            'mask': {color: '#404040', loadSpeed: 'normal', opacity: 0.7},
            'top': '25%',
            'onBeforeLoad': function(event) {
              $('.modalBox-flash').empty();
            }
          });
          $('#app-urls-table .icon-tip').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
        }
        if (tab == '#files') {
          if (typeof app_download_bits_url == 'undefined') {
            $('.invoke-modalBox').empty().hide();
          } else {
            $('.invoke-modalBox').html('<a href="' + app_download_bits_url + '" class="button">' + I18n.t('apps.js.download_bits') + '</a>').show();
          }
        }
      }
    });
    $('#set-var-form .help').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
    $('#set-var-form').validator({'effect': 'below_field_error', 'inputEvent': 'blur', 'lang': validatorTools_lang});
    $(document)
      .on('ajax:beforeSend', '#set-var-form', function(evt, xhr, settings) {
        var validator = $('#set-var-form').data('validator');
        if (!validator.checkValidity()) return false;
        request_processed = false;
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('assets.js.ajax_processing')});
      })
      .on('ajax:success', '#set-var-form', function(evt, data, status, xhr) {
        if (request_processed == true) {
          $(this).find('input[type="text"]').val('');
        }
      })
      .on('ajax:error', '#set-var-form', function(evt, xhr, status, error) {
        request_processed = true;
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#set-var-form', function(evt, xhr, status) {;
        if (request_processed == true) {
          addEnvvar_trigger.eq(0).overlay().close();
        }
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('apps.js.add_envvar')});
      });
    $(document)
      .on('ajax:beforeSend', '#unset-var-link', function(evt, xhr, settings) {
        $(this).find('img').attr({ src : '<%= asset_path('wait.gif') %>'}).removeClass('delete');
      })
      .on('ajax:error', '#unset-var-link', function(evt, xhr, status, error) {
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#unset-var-link', function(evt, xhr, status) {
        $(this).find('img').attr({ src : '<%= asset_path('s.gif') %>'}).addClass('delete');
      });
    $('#bind-service-form .help').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
    $('#bind-service-form').validator({'effect': 'below_field_error', 'inputEvent': 'blur', 'lang': validatorTools_lang});
    $(document)
      .on('ajax:beforeSend', '#bind-service-form', function(evt, xhr, settings) {
        var validator = $('#bind-service-form').data('validator');
        if (!validator.checkValidity()) return false;
        request_processed = false;
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('assets.js.ajax_processing')});
      })
      .on('ajax:success', '#bind-service-form', function(evt, data, status, xhr) {
        if (request_processed == true) {
          $(this).find('select').val('');
        }
      })
      .on('ajax:error', '#bind-service-form', function(evt, xhr, status, error) {
        request_processed = true;
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#bind-service-form', function(evt, xhr, status) {
        if (request_processed == true) {
          bindService_trigger.eq(0).overlay().close();
        }
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('apps.js.add_service')});
      });
    $(document)
      .on('ajax:beforeSend', '#unbind-service-link', function(evt, xhr, settings) {
        $(this).find('img').attr({ src : '<%= asset_path('wait.gif') %>'}).removeClass('delete');
      })
      .on('ajax:error', '#unbind-service-link', function(evt, xhr, status, error) {
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#unbind-service-link', function(evt, xhr, status) {
        $(this).find('img').attr({ src : '<%= asset_path('s.gif') %>'}).addClass('delete');
      });
    $('#map-url-form .help').tooltip({'effect': 'fade', 'tipClass': 'help-tip'});
    $('#map-url-form').validator({'effect': 'below_field_error', 'inputEvent': 'blur', 'lang': validatorTools_lang});
    $(document)
      .on('ajax:beforeSend', '#map-url-form', function(evt, xhr, settings) {
        var validator = $('#map-url-form').data('validator');
        if (!validator.checkValidity()) return false;
        request_processed = false;
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('assets.js.ajax_processing')});
      })
      .on('ajax:success', '#map-url-form', function(evt, data, status, xhr) {
        if (request_processed == true) {
          $(this).find('input[type="url"]').val('');
        }
      })
      .on('ajax:error', '#map-url-form', function(evt, xhr, status, error) {
        request_processed = true;
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#map-url-form', function(evt, xhr, status) {
        if (request_processed == true) {
          addURL_trigger.eq(0).overlay().close();
        }
        $(this).find('.modalBox-submit input[type="submit"]').attr({value: I18n.t('apps.js.add_url')});
      });
    $(document)
      .on('ajax:beforeSend', '#unmap-url-link', function(evt, xhr, settings) {
        $(this).find('img').attr({ src : '<%= asset_path('wait.gif') %>'}).removeClass('delete');
      })
      .on('ajax:error', '#unmap-url-link', function(evt, xhr, status, error) {
        $('#flash-content').empty();
        $('#flash-content').append('<div class="alert">' + I18n.t('assets.js.ajax_error') + '</div>');
        $('#flash').fadeIn('slow');
      })
      .on('ajax:complete', '#unmap-url-link', function(evt, xhr, status) {
        $(this).find('img').attr({ src : '<%= asset_path('s.gif') %>'}).addClass('delete');
      });
  }
});